<template>
  <div class="list-container">
    <!-- immediate-check 是否在初始化时立即执行滚动位置检查 -->
    <van-list
      v-model="loading"
      :immediate-check="false"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <!-- 文章列表 -->
        <article-item
        v-for="item in articlesList"
        :key="item.art_id"
        :articles-list="item"
        @click.native="getDetail(item.art_id)"
        />
      </van-pull-refresh>
    </van-list>
  </div>
</template>

<script>
/**
 * 1. 发送数据的组件位置 采取再 article-list
 * 2. list vs item
 * 3. list - 智能组件 - 和后端交互获取数据 组装木偶组件 给他们下发数据
 * 4. item - 木偶组件(ui组件) - 就收不同数据显示ui效果
 */
import ArticleItem from './home-list-item.vue'
import { getArticlesApi } from '@/api'
export default {
  name: 'home-list',
  props: {
    ChannelsId: {
      type: Number,
      default: () => {}
    }
  },
  components: {
    ArticleItem
  },
  data () {
    return {
      // 下拉加载状态
      isLoading: false,
      // 控制加载状态
      finished: false,
      loading: false,
      // 初始化列表
      articlesList: [],
      // 当前时间
      timestamp: new Date().getTime()
    }
  },
  methods: {
    // 点击详情
    getDetail (artId) {
      this.$router.push({
        path: '/detail',
        query: {
          id: artId
        }
      })
    },
    // 初始化页面
    async fetchArticlesList () {
      // console.log(this.ChannelsId)
      const { data } = await getArticlesApi({
        channelId: this.ChannelsId,
        timestamp: this.timestamp
      })
      // console.log(data, '文章列表')
      this.articlesList = data.results
      this.timestamp = data.pre_timestamp
    },
    // 下拉刷新
    async onRefresh () {
      const { data } = await getArticlesApi({
        channelId: this.ChannelsId,
        timestamp: new Date().getTime()
      })
      // console.log(data, '文章列表')
      this.articlesList = data.results
      this.timestamp = data.pre_timestamp
      this.isLoading = false
    },
    // 上拉加载下一页
    async onLoad () {
      // 页面触底 触发onload事件  请求数据
      const { data } = await getArticlesApi({
        channelId: this.ChannelsId,
        timestamp: this.timestamp
      })
      // 把请求回来的数据和已有数据进行拼接
      this.articlesList = [...this.articlesList, ...data.results]
      // 更新最后一次刷新时间
      this.timestamp = data.pre_timestamp
      // 数据加载完毕将 loading 设置为true 停止动画
      this.loading = false
      // 自行判断 全部数据加载完毕 finished设置为true
      if (data.pre_timestamp === null) {
        this.finished = true
      }
    }
  },
  created () {
    this.fetchArticlesList()
  }
}
</script>

<style scoped>
  .list-container{
    position: fixed;
    top:44px;
    bottom:50px;
    width: 100%;
    overflow: auto;
  }
</style>
